<template>
  <div>
    <div class="pageTitleWhole">
      <a-breadcrumb>
        <a-breadcrumb-item>应付明细</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <div class="pageTabsWhole" style="margin-top:24px;">
      <a-spin :spinning="loading">
        <a-tabs
          class="table_tab"
          defaultActiveKey
          :animated="false"
          :tabBarStyle="{margin:0}"
          :tabBarGutter="16"
          @change="onChangeStatus"
        >
          <a-tab-pane v-for="v in tabs" :key="v.key" :tab="v.title"></a-tab-pane>
        </a-tabs>
      </a-spin>
    </div>
    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="结算对象">
              <a-input v-model="searchForm.custName" />
            </a-form-item>
            <a-form-item label="费用类型">
              <a-select v-model="searchForm.feeTypeId" class="selectInputWidth">
                <a-select-option value>请选择</a-select-option>
                <a-select-option v-for="(v,k) in feeList" :key="k" :value="v.id">{{v.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="statusKey===''" label="状态">
              <a-select v-model="searchForm.status" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option :key="1">未对账</a-select-option>
                <a-select-option :key="2">已对账</a-select-option>
                <a-select-option :key="3">已结清</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="结算类型">
              <a-select v-model="searchForm.settlementType" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="v in settlementTypeList" :key="v.key">{{v.value}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-input-group compact>
                <a-select v-model="searchForm.timeType" class="selectWidth">
                  <a-select-option :key="1">费用录入日期</a-select-option>
                  <a-select-option :key="2">完成订单日期</a-select-option>
                </a-select>
                <a-range-picker :value="searchForm.dateRange" @change="onDateChange">
                  <a-icon slot="suffixIcon" type="calendar" />
                </a-range-picker>
              </a-input-group>
            </a-form-item>
            <a-form-item label="公司编号/运单号/箱号">
              <a-input v-model="searchForm.orderCodeOrContainerNo" />
            </a-form-item>
            <a-form-item label="订单类型">
              <a-select v-model="searchForm.orderType" class="selectInputWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="v in OrderOptions" :key="v.key">{{v.title}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="业务类型">
              <a-select v-model="searchForm.belongCompany" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option key="JIA_HUA">佳华业务</a-select-option>
                <a-select-option key="JIA_TE">自主业务</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="运输条款">
              <a-select v-model="searchForm.transportTerms" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option key="DO-DO">DO-DO</a-select-option>
                <a-select-option key="DO-CY">DO-CY</a-select-option>
                <a-select-option key="CY-DO">CY-DO</a-select-option>
                <a-select-option key="CY-CY">CY-CY</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="付款银行">
              <a-input v-model="searchForm.transactionBank" />
            </a-form-item>
            <a-form-item label="车辆">
              <a-select
                class="selectInputWidth"
                show-search
                :show-arrow="false"
                :filter-option="false"
                :default-active-first-option="false"
                :not-found-content="null"
                v-model="searchForm.tractorId"
                @search="handleCarNameChange"
              >
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="d in carLikeData" :key="d.truckId">{{ d.truckNumber }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="司机">
              <a-select
                class="selectInputWidth"
                show-search
                :show-arrow="false"
                :filter-option="false"
                :default-active-first-option="false"
                :not-found-content="null"
                v-model="searchForm.driverId"
                @search="queryDriverDown"
              >
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="d in driverLikeData" :key="d.driverId">{{ d.name }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="客户名称">
              <a-input v-model="searchForm.customerName" />
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="exportExcel">导出Excel</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="batchCompanyids">司编号批量查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="generateBill">生成账单</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="addToBill">添加到账单</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="setViewFields">设置查看字段</a-button>
            </a-form-item>
          </a-form>
        </a-col>

        <a-col :span="24">
          <a-card style="text-align:center; margin-top:24px;">
            <a-col :span="8" class="assent">
              <div class="assent_mes">费用条目数</div>
              <div class="assent_shu">{{info.number || '--'}}</div>
            </a-col>
            <a-col :span="8">
              <div class="assent_mes">人民币总金额（元）</div>
              <div class="assent_shu">{{info.amountCNY || '--'}}</div>
            </a-col>
            <a-col :span="8">
              <div class="assent_mes">美元总金额（元）</div>
              <div class="assent_shu">{{info.amountUSD || '--'}}</div>
            </a-col>
          </a-card>
        </a-col>

        <a-col :span="24">
          <a-card style="margin-top:12px;">
            选中的明细总金额（元）：￥
            <span style="color: red; font-size: 1.2em;">{{cn}}</span> ；$
            <span style="color: red; font-size: 1.2em;">{{usd}}</span>
          </a-card>
        </a-col>

        <a-col :span="24" style="margin-top:24px;">
          <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, getCheckboxProps: getCheckboxProps }"
            :columns="columns"
            :loading="loading"
            :data-source="tableData"
            :pagination="pagination"
            :scroll="scroll"
            row-key="id"
          >
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <template slot="code" slot-scope="text, record">
              <a @click="toCompanyCode(record.businessId)">{{text}}</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 设置查看字段 -->
    <a-modal
      :visible="fieldVisible"
      title="设置查看字段"
      centered
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-checkbox-group @change="onCheckChange" :defaultValue="defaultValues">
        <a-row>
          <a-col v-for="(box, i) in fields" :key="i" :span="12" style="margin-bottom:3px;">
            <a-checkbox :value="box.key">{{box.value}}</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-modal>

    <!-- 生成账单 -->
    <a-modal
      :visible="generateVisible"
      title="确认生成账单"
      centered
      :destroyOnClose="true"
      :maskClosable="false"
      :confirmLoading="confirmLoading"
      @ok="handleOk2"
      @cancel="handleCancel2"
    >
      <a-form-model
        ref="rulesForm"
        :model="generateForm"
        :rules="rules"
        :labelCol="{span: 8}"
        :wrapperCol="{span: 14}"
      >
        <a-form-model-item label="收款单位">
          <router-link :to="{path: customUrl}" target="_blank">{{customName}}</router-link>
        </a-form-model-item>
        <a-form-model-item label="账期截止日期" prop="endDate">
          <a-date-picker @change="onChangeEndDate">
            <a-icon slot="suffixIcon" type="calendar" />
          </a-date-picker>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 添加到账单 -->
    <addToBillModal
      :visible="addToVisible"
      :billCostIds="billCostIds"
      :cc="cc"
      @setVisible="setAddToMadal"
    />

    <!-- 司编号批量查询 -->
    <a-modal
      :visible="batchVisible"
      title="司编号批量查询"
      centered
      :destroyOnClose="true"
      :maskClosable="false"
      @cancel="handleCancel3"
    >
      <template slot="footer">
        <a-button type="primary" @click="handleOk3">查询</a-button>
      </template>
      <a-row>
        <a-col :span="22" :offset="1">
          <a-textarea :rows="6" v-model="orderCodeBatch"></a-textarea>
          <small>*输入时请注意，每行一个司编号</small>
        </a-col>
      </a-row>
    </a-modal>
  </div>
</template>

<script>
import { mixin } from '@/common/common'
import debounce from 'lodash/debounce'
import store from 'store'
import addToBillModal from '@/page/financialCenter/addToBillModal'
import { queryFeeTypeList, queryTruckNumberDown, queryDriverDown } from '@/api'
import { queryJTBillCostList, createBill } from '@/api/financialCenter'
import { commonExport } from '@/api/request'
const fomrMessage = `必填项不能为空`
const tabs = [
  { key: '', title: '全部明细' },
  { key: 1, title: '未对账' },
  { key: 2, title: '已对账' },
  { key: 3, title: '已结清' }
]
const typeOptions = [
  { key: 1, title: '公司编号' },
  { key: 2, title: '运单号' },
  { key: 3, title: '箱号' }
]
// 订单类型
const OrderOptions = [
  { key: 'DOMESTIC_TRADE_EXPORTS', title: '内贸出口订单' },
  { key: 'DOMESTIC_TRADE_IMPORTS', title: '内贸进口订单' },
  { key: 'FOREIGN_TRADE_EXPORTS', title: '外贸出口订单' },
  { key: 'FOREIGN_TRADE_IMPORTS', title: '外贸进口订单' },
  { key: 'UNITED_TRANSPORT_EXPORTS', title: '联运出口订单' },
  { key: 'UNITED_TRANSPORT_IMPORTS', title: '联运进口订单' },
  { key: 'PURE_LAND_TRANSPORTS', title: '纯陆运订单' }
]
const defaultSearchForm = (status) => ({
  status,
  feeType: 2,
  custName: '',
  feeTypeId: '',
  settlementType: '',
  queryType: 1, // 查询方式：1公司编号、2运单号、3箱号
  orderCodeOrContainerNo: '',
  orderType: '',
  belongCompany: '',
  searchStartTime: null,
  searchEndTime: null,
  transportTerms: '', // 运输条款
  transactionBan: '', // 付款银行
  timeType: 1,
  dateRange: [null, null],
  driverId: '',
  tractorId: '',
  customerName: ''
})

export default {
  mixins: [mixin],
  data () {
    this.handleCarNameChange = debounce(this.handleCarNameChange, 800)
    this.queryDriverDown = debounce(this.queryDriverDown, 800)

    const columnsWhole = [
      {
        title: '序号',
        width: 60,
        scopedSlots: { customRender: 'rn' }
      },
      {
        title: '公司编号',
        dataIndex: 'truckOrderCode',
        scopedSlots: { customRender: 'code' }
      },
      {
        title: '客户名称',
        dataIndex: 'customerName',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '费用类型',
        dataIndex: 'feeName'
      },
      {
        title: '金额（元）',
        dataIndex: 'amount',
        customRender: (text, record, index) => {
          return record.currencyType === 'USD' ? <span class='t_money t_money1'>$ {text}</span> : text
        }
      },
      {
        title: '结算对象',
        dataIndex: 'custName'
      },
      {
        title: '加油卡',
        dataIndex: 'cardNo',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        customRender: (text, record, index) => {
          return text === 1 ? <span style="color: red">未对账</span> : (text === 2 ? <span style="color: green">已对账</span> : (text === 3 ? '已结清' : ''))
        },
        _needName: true
      },
      {
        title: '录入费用日期',
        dataIndex: 'costTime',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '完成订单日期',
        dataIndex: 'completeTime',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '车辆',
        dataIndex: 'truckNumber',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '司机',
        dataIndex: 'driverName',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '运单号',
        dataIndex: 'seagoingShipOrderCode',
        width: 150,
        ellipsis: true,
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '箱号',
        dataIndex: 'containerNo',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '封号',
        dataIndex: 'containerSealNo',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '箱型箱量',
        dataIndex: 'containerType',
        customRender: (text, record, index) => {
          return text ? `${text}*1` : '--'
        }
      },
      {
        title: '发票号',
        dataIndex: 'invoiceNo',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '开票时间',
        dataIndex: 'lastInvoiceDate',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '付款银行',
        dataIndex: 'transactionBank',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '订单类型',
        dataIndex: 'orderType',
        customRender: (text, record, index) => {
          const t = OrderOptions.filter(v => v.key === text)[0]
          return t ? t.title : '--'
        },
        _needName: true
      },
      {
        title: '结算类型',
        dataIndex: 'settlementType',
        customRender: (text, record, index) => {
          return this.checkSettlementTypeName(text)
        },
        _needName: true
      },
      {
        title: '运输条款',
        dataIndex: 'transportTerms',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '货名',
        dataIndex: 'goodsName',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '货重（吨）',
        dataIndex: 'goodsWeight',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '始发港',
        dataIndex: 'startPortName',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '目的港',
        dataIndex: 'endPortName',
        customRender: (text, record, index) => {
          return text || '--'
        }
      }
    ]

    return {
      tabs,
      typeOptions,
      OrderOptions,
      statusKey: '',
      feeList: [],
      carLikeData: [],
      driverLikeData: [],
      searchForm: defaultSearchForm(''),
      columnsWhole,
      columns: [],
      scroll: { x: '250%', y: 500 },
      loading: false,
      tableData: [],
      info: {},
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      selectedRowKeys: [],
      // 设置查看字段
      fieldVisible: false,
      fields: [],
      defaultValues: [],
      currentValues: null,
      // 生成账单
      generateVisible: false,
      customName: '',
      customUrl: '',
      generateForm: {
        endDate: null
      },
      rules: {
        endDate: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }]
      },
      confirmLoading: false,
      // 添加到账单
      addToVisible: false,
      billCostIds: [],
      cc: {},
      // batch
      orderCodeBatch: '',
      batchVisible: false
    }
  },
  components: {
    addToBillModal
  },
  computed: {
    cn () {
      const selectedFees = this.tableData.filter(v => this.selectedRowKeys.includes(v.id))
      if (selectedFees.length > 0) {
        let l = 0
        selectedFees.forEach(v => {
          if (v.currencyType === 'CNY') {
            l += v.amount
          }
          return v
        })
        return l
      }
      return 0
    },
    usd () {
      const selectedFees = this.tableData.filter(v => this.selectedRowKeys.includes(v.id))
      if (selectedFees.length > 0) {
        let l = 0
        selectedFees.forEach(v => {
          if (v.currencyType === 'USD') {
            l += v.amount
          }
          return v
        })
        return l
      }
      return 0
    }
  },
  methods: {
    onChangeStatus (key) {
      this.statusKey = key
      this.searchForm = defaultSearchForm(key)
      this.handleSubmit1()
    },
    initFeeTypeRequest (e) {
      queryFeeTypeList(e)
        .then(res => {
          this.feeList = res.data
        })
        .catch(rs => { })
    },
    onDateChange (date, dataStr) {
      this.searchForm.searchStartTime = dataStr[0]
      this.searchForm.searchEndTime = dataStr[1]
      this.searchForm.dateRange = [date[0], date[1]]
    },
    handleCarNameChange (nameLike) { // 所有牵引车
      if (nameLike) {
        queryTruckNumberDown({
          truckNumber: nameLike,
          tractorOrTrailer: 1
        }).then(rsp => {
          this.carLikeData = rsp.data
        })
      } else {
        this.carLikeData = []
      }
    },
    queryDriverDown (word) {
      if (word) {
        queryDriverDown({ word }).then(rsp => {
          this.driverLikeData = rsp.data
        })
      } else {
        this.driverLikeData = []
      }
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.selectedRowKeys = []
      this.loading = true
      queryJTBillCostList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
        this.info = {
          number: rsp.data.number,
          amountCNY: rsp.data.amountCNY,
          amountUSD: rsp.data.amountUSD
        }
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          pageSizeOptions: ['10', '100', '250', '500'],
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      })
    },
    setViewFields () {
      this.fields = this.columnsWhole.map(v => {
        if (v.dataIndex) {
          return {
            key: v.dataIndex,
            value: v.title
          }
        }
      }).filter(v => v)
      this.fieldVisible = true
    },
    onCheckChange (checkedValues) {
      this.currentValues = checkedValues
    },
    handleOk () {
      this.defaultValues = this.currentValues
      store.set('jt', this.currentValues)
      this.columns = this.columnsWhole.filter((v, i) => {
        return i === 0 || this.currentValues.includes(v.dataIndex)
      })
      this.scroll.x = 150 * this.columns.length
      this.fieldVisible = false
    },
    handleCancel () {
      this.fieldVisible = false
    },
    exportExcel () {
      commonExport('/bill/exportJTBillCostList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: [...this.columnsWhole, {
          title: '币种',
          dataIndex: 'currencyType'
        }]
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    getCheckboxProps (record) {
      return {
        props: {
          disabled: record.status !== 1
        }
      }
    },
    checkBills () {
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请先选择费用明细')
        return false
      }

      const selectedFees = this.tableData.filter(v => this.selectedRowKeys.includes(v.id))
      const custName = selectedFees[0].custName
      if (!selectedFees.every(v => v.custName === custName)) {
        this.$message.error('同一账单中，结算对象必须一致')
        return false
      }

      const currencyType = selectedFees[0].currencyType
      if (!selectedFees.every(v => v.currencyType === currencyType)) {
        this.$message.error('同一账单中，币种必须一致')
        return false
      }

      return true
    },
    onChangeEndDate (date, dataStr) {
      this.generateForm.endDate = dataStr
    },
    generateBill () {
      if (!this.$root._bc.createBill) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.checkBills()) {
        const t = this.tableData.filter(v => this.selectedRowKeys.includes(v.id))[0]
        this.customName = t.custName
        this.customUrl = `/landCenter/payableSettlementObject/${t.custId}`
        if (t.custType && ~t.custType.indexOf('CUSTOMER')) {
          this.customUrl = `/landCenter/customManage/${t.custId}`
        }
        this.generateVisible = true
      }
    },
    handleOk2 () { // 生成账单
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          createBill({
            billCostIds: this.selectedRowKeys,
            ...this.generateForm
          }).then(rsp => {
            this.$message.success('生成账单成功')
            this.confirmLoading = false
            this.generateVisible = false
            this.handleSubmit()
          }).catch(() => { this.confirmLoading = false })
        }
      })
    },
    handleCancel2 () {
      this.generateVisible = false
    },
    addToBill () { // 添加到账单
      if (!this.$root._bc.addToBill) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.checkBills()) {
        this.billCostIds = this.selectedRowKeys
        const target = this.tableData.filter(v => this.selectedRowKeys.includes(v.id))[0]
        this.cc = {
          custName: target.custName,
          currencyType: target.currencyType,
          businessType: 'JIA_TE',
          feeType: 2
        }
        this.addToVisible = true
      }
    },
    setAddToMadal (f) {
      if (f) {
        this.handleSubmit()
      }
      this.addToVisible = false
    },
    toCompanyCode (businessId) {
      window.open(`/landCenter/orderDispatch/${businessId}`, '_blank')
    },
    batchCompanyids () { // 司编号批量查询
      this.batchVisible = true
    },
    handleOk3 () {
      this.batchVisible = false
      this.searchForm.orderCodeBatch = this.orderCodeBatch
      this.handleSubmit()
    },
    handleCancel3 () {
      this.batchVisible = false
      this.orderCodeBatch = this.searchForm.orderCodeBatch
    }
  },
  created () {
    this.initFeeTypeRequest({
      status: 1,
      belongCompany: 'JIA_TE',
      feeType: 2
    })

    // 读取设置的可见字段
    this.currentValues = this.defaultValues = this.currentValues || store.get('jt') || this.columnsWhole.map(v => v.dataIndex).filter(v => v)
    this.columns = this.columnsWhole.filter((v, i) => {
      return i === 0 || this.currentValues.includes(v.dataIndex)
    })
    this.scroll.x = 150 * this.columns.length
  },
  mounted () {
    this.$nextTick(() => {
      this.handleSubmit()
    })
  }
}
</script>

<style lang="less" scoped>
</style>
